package cn.wmw.xyy.mq.consumer;

import cn.wmw.xyy.bo.CourseOrderExtParamsBo;
import cn.wmw.xyy.domain.CourseOrder;
import cn.wmw.xyy.exception.GlobalException;
import cn.wmw.xyy.exception.GlobalExceptionEnum;
import cn.wmw.xyy.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "order-handler-group",
        topic = "pay-local-handler-topic",
        selectorExpression = "pay-local-handler-tag",
        messageModel = MessageModel.BROADCASTING
)
public class OrderHandlerConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body.length == 0) {
            log.error("报异常啦，没得到参数");
            throw new GlobalException(GlobalExceptionEnum.ERROR);
        }

        CourseOrderExtParamsBo courseOrderExtParamsBo = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderExtParamsBo.class);

        // 2.业务校验
        String orderNo = courseOrderExtParamsBo.getOrderNo();
        CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);

        if (courseOrder == null){
            log.error("报异常啦，没得到订单号" + orderNo);
            return;
        }
        Integer statusOrder = courseOrder.getStatusOrder();
        if (!CourseOrder.WAIT_PAY.equals(statusOrder)){
            log.error("报异常啦，赶快修bug");
            return;
        }
        courseOrder.setStatusOrder(CourseOrder.SUCCESS_PAY);
        courseOrder.setUpdateTime(new Date());
        courseOrderService.updateById(courseOrder);
    }
}
